package com.ruoyi.project.WebMoudle.WxShop.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.ruoyi.common.constant.WxConstant;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.project.WebMoudle.ImgFiles.domain.ImgFiles;
import com.ruoyi.project.WebMoudle.ImgFiles.service.IImgFilesService;
import com.ruoyi.project.WebMoudle.ShopOffUser.domain.ShopOffUser;
import com.ruoyi.project.WebMoudle.ShopOffUser.service.IShopOffUserService;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopSuser;
import com.ruoyi.project.WebMoudle.ShopSuser.domain.ShopVo;
import com.ruoyi.project.WebMoudle.ShopSuser.service.IShopSuserService;
import com.ruoyi.project.WebMoudle.WxShop.domain.ShopApply;
import com.ruoyi.project.WebMoudle.WxShop.domain.ShopEntity;
import com.ruoyi.project.WebMoudle.WxShopWords.domain.WxShopWords;
import com.ruoyi.project.WebMoudle.WxShopWords.service.IWxShopWordsService;
import com.ruoyi.project.WebMoudle.WxUser.domain.WxUser;
import com.ruoyi.project.WebMoudle.WxUser.service.IWxUserService;
import com.ruoyi.project.WxMoudle.Bases.HttpUtil;
import com.ruoyi.project.WxMoudle.Bases.WeixinConfig;
import com.ruoyi.project.WxMoudle.WebSocket.WebSocketServer;
import com.ruoyi.project.system.dept.service.IDeptService;
import com.ruoyi.project.system.post.service.IPostService;
import com.ruoyi.project.system.role.domain.Role;
import com.ruoyi.project.system.role.service.IRoleService;
import com.ruoyi.project.system.user.domain.User;
import com.ruoyi.project.system.user.service.IUserService;
import com.ruoyi.project.system.user.service.UserServiceImpl;
import jdk.nashorn.internal.ir.debug.PrintVisitor;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.WebMoudle.WxShop.domain.WxShop;
import com.ruoyi.project.WebMoudle.WxShop.service.IWxShopService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 商家店铺Controller
 *
 * @author ruoyi
 * @date 2020-06-18
 */
@Controller
@RequestMapping("/WxShop/WxShop")
public class WxShopController extends BaseController {
    private String prefix = "WxShop/WxShop";

    @Autowired
    private IWxShopService wxShopService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IShopSuserService shopSuserService;

    @Autowired
    private IImgFilesService imgFilesService;

    @Autowired
    private IWxUserService wxUserService;

    @Autowired
    private IWxShopWordsService wordsService;

    @Autowired
    private IUserService sysUserService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IShopOffUserService offUserService;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private IUserService userService;



    @RequiresPermissions("WxShop:WxShop:view")
    @GetMapping("view")
    public String view() {
        return prefix + "/WxShop";
    }

    @RequiresPermissions("WxShop:WxShop:view")
    @GetMapping("/view02")
    public String view02() {
        return prefix + "/WxShop02";
    }

    @RequiresPermissions("WxShop:WxShop:view")
    @GetMapping("/offShop")
    public String offShop() {
        return prefix + "/offShop";
    }

    @GetMapping("/oneShop")
    public String oneShop() {
        return prefix + "/oneShop";
    }

    @GetMapping("/showMapinfo")
    public String showMapinfo()
    {
        return prefix + "/showMapinfo";
    }

    @RequiresPermissions("WxShop:WxShop:exchange")
    @GetMapping("/exchange")
    public String exchange(ModelMap mmap) {
        ShopSuser shopSuser = shopSuserService.selectOneShopId(getUserId());
        if (StringUtils.isNotNull(shopSuser)){
            WxShop wxShop = wxShopService.selectWxShopById(shopSuser.getShopId());
            mmap.put("shopId",shopSuser.getShopId());
            mmap.put("wxUserId",wxShop.getWxUserId());
        }else {
            mmap.put("shopId",0);
            mmap.put("wxUserId",0);
        }
        return prefix + "/exchange";
    }

    /**
     * 查询商家店铺列表
     */
    @RequiresPermissions("WxShop:WxShop:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(WxShop wxShop) {
        startPage();
        List<WxShop> list = wxShopService.selectWxShopList(wxShop);
        return getDataTable(list);
    }

    @RequiresPermissions("WxShop:WxShop:list")
    @PostMapping("/isShowList")
    @ResponseBody
    public TableDataInfo isShowList(WxShop wxShop) {
        startPage();
        List<WxShop> list = wxShopService.isShowList(wxShop);
        return getDataTable(list);
    }

    @RequiresPermissions("WxShop:WxShop:list")
    @PostMapping("/offList")
    @ResponseBody
    public TableDataInfo offList(WxShop wxShop) {
        startPage();
        List<WxShop> list = wxShopService.offList(wxShop);
        return getDataTable(list);
    }

    /*查询待审核商铺的数量*/
    @RequestMapping("/queryApplyShopCount")
    @ResponseBody
    public int queryApplyShopCount() {
       int i = wxShopService.queryApplyShopCount();
       return i;
    }

    /**
     * 查询当前账号商家店铺
     */
    @RequestMapping("/selectShopId")
    @ResponseBody
    public Object selectShopId() {
        ShopSuser shopSuser = shopSuserService.selectOneShopId(getUserId());
        if(StringUtils.isNotNull(shopSuser)){
            return shopSuser.getShopId();
        }
        return 0;
    }
    /**
     * 查询待审核和审核失效的商铺
     *
     * @param wxShop
     * @return
     */
    @RequiresPermissions("WxShop:WxShop:list")
    @PostMapping("/list02")
    @ResponseBody
    public TableDataInfo list02(WxShop wxShop) {
        startPage();
        List<WxShop> list = wxShopService.selectWxShopList02();
        return getDataTable(list);
    }

    /**
     * 导出商家店铺列表
     */
    @RequiresPermissions("WxShop:WxShop:export")
    @Log(title = "商家店铺", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(WxShop wxShop) {
        List<WxShop> list = wxShopService.selectWxShopList(wxShop);
        ExcelUtil<WxShop> util = new ExcelUtil<WxShop>(WxShop.class);
        return util.exportExcel(list, "WxShop");
    }

    /**
     * 新增商家店铺
     */
    @GetMapping("/add")
    public String add() {
        return prefix + "/add";
    }

    /**
     * 新增保存商家店铺
     */
    @RequiresPermissions("WxShop:WxShop:add")
    @Log(title = "商家店铺", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(WxShop wxShop) {
        return toAjax(wxShopService.insertWxShop(wxShop));
    }

    /**
     * 修改商家店铺
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap) {
        WxShop wxShop = wxShopService.selectWxShopById(id);
        String myWords = "";
        if (StringUtils.isNotEmpty(wxShop.getWordsIds())) {
            myWords = wxShop.getWordsIds();
        }
        List<WxShopWords> wordsList = wordsService.selectSelfList(myWords);

        mmap.put("wxShop", wxShop);
        mmap.put("wordsList", wordsList);

        return prefix + "/edit";
    }

    /**
     * 修改商家店铺
     */
    @GetMapping("/editShop/{id}")
    public String editShop(@PathVariable("id") Long id, ModelMap mmap) {
        WxShop wxShop = wxShopService.selectWxShopById(id);
        List<WxShopWords> wordsList = wordsService.selectSelfList(wxShop.getWordsIds());

        mmap.put("wxShop", wxShop);
        mmap.put("wordsList", wordsList);
        return prefix + "/editShop";
    }

    /**
     * 编辑商家店铺
     */
    @RequiresPermissions("WxShop:WxShop:edit")
    @GetMapping("/editOneShop")
    public String editOneShop(ModelMap mmap) {
        ShopSuser shopSuser = shopSuserService.selectOneShopId(getSysUser().getUserId());   //查询当前登录人的商铺id
        WxShop wxShop = new WxShop();
        List<WxShopWords> wordsList = new ArrayList<>();
        if (StringUtils.isNotNull(shopSuser)) {
            wxShop = wxShopService.selectWxShopById(shopSuser.getShopId());
            wordsList = wordsService.selectSelfList(wxShop.getWordsIds());
        }
        mmap.put("wxShop", wxShop);
        mmap.put("wordsList", wordsList);
        return prefix + "/editShop";
    }

    /**
     * 审核商铺
     */
    @GetMapping("/applyValid/{id}")
    public String applyValid(@PathVariable("id") Long id, ModelMap mmap) {
        WxShop wxShop = wxShopService.selectWxShopById(id);
        List<Role> roles = roleService.selectShopRole();   //查询商家角色
        mmap.put("roles", roles);
        mmap.put("wxShop", wxShop);
        return prefix + "/apply";
    }


    @Log(title = "修改商家店铺参数", businessType = BusinessType.UPDATE)
    @PostMapping("/editShop")
    @ResponseBody
    @Transactional
    public AjaxResult editShop(MultipartFile[] logoImgFiles, WxShop wxShop) throws IOException {
        if (logoImgFiles.length > 0) {
            for (MultipartFile file : logoImgFiles) {
                String upload = FileUploadUtils.upload(file);
                ImgFiles img = new ImgFiles();
                img.setImgName(file.getOriginalFilename());
                img.setImgPath(upload);
                imgFilesService.insertImgFiles(img);
                if (StringUtils.isNotEmpty(wxShop.getShopLogo())) {
                    wxShop.setShopLogo(wxShop.getShopLogo() + "," + img.getId());
                } else {
                    wxShop.setShopLogo(img.getId() + "");
                }
            }
        }
        WxShop ws = wxShopService.selectWxShopById(wxShop.getId());
        if (!ws.getShopTel().equals(wxShop.getShopTel())){   //手机号不一致
            Long wxUserId = ws.getWxUserId();    //商铺管理员
            ShopSuser shopSuser = shopSuserService.selectEntityByWidAndSid(wxUserId, ws.getId());
            User user = new User();
            user.setUserId(shopSuser.getSysUserId());
            user.setPhonenumber(wxShop.getShopTel());
            userService.updateUserInfo(user);
        }
        return toAjax(wxShopService.updateWxShop(wxShop));
    }

    /**
     * 修改店
     */
    @RequiresPermissions("WxShop:WxShop:edit")
    @Log(title = "商家店铺", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(WxShop wxShop) {
        return toAjax(wxShopService.updateWxShop(wxShop));
    }

    /**
     * 审核提交
     *
     * @param shopApply
     * @return
     */
    @Log(title = "商家店铺", businessType = BusinessType.UPDATE)
    @PostMapping("/apply")
    @ResponseBody
    @Transactional
    public AjaxResult applySave(ShopApply shopApply) throws Exception {
        if (StringUtils.isNotEmpty(shopApply.getIsValid())) {
            if (WxConstant.GOOD_VALID.equals(shopApply.getIsValid())) {    //通过
                //审核通过
                int i = wxShopService.applyWxShop(shopApply);
                if (i == 1) {//审核成功
                    webSocketServer.sendAll("发送消息");
                    return toAjax(1);
                } else if (i == 22) {
                    //登录名不唯一
                    return AjaxResult.error("登录名重复");
                } else if (i == 44) {
                    //未确认角色
                    return AjaxResult.error("未确认角色");
                }else {
                    //系统错误
                    return toAjax(0);
                }
            } else if (WxConstant.BED_VALID.equals(shopApply.getIsValid())) {   //驳回
                WxUser user = new WxUser();
                user.setId(shopApply.getWxUserId());
                //审核不通过
                wxUserService.updateWxUser(user);

                WxShop sa = new WxShop();
                sa.setId(shopApply.getId());
                sa.setIsValid("2");
                sa.setRemarks(shopApply.getRemarks());
                int i = wxShopService.updateWxShop(sa);
                if(i>0){
                    webSocketServer.sendAll("发送消息");
                }
                return toAjax(i);
            } else {
                //未审核
                return AjaxResult.error("请及时审核");
            }
        } else {
            return AjaxResult.error("审核失效");
        }
    }

    /**
     * 删除商家店铺
     */
    @RequiresPermissions("WxShop:WxShop:remove")
    @Log(title = "商家店铺", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(wxShopService.deleteWxShopByIds(ids));
    }

    /**
     * 平台注销商家店铺
     *
     * @param shopId
     * @param
     * @return
     * @throws Exception
     */
    @PostMapping("/offShop")
    @ResponseBody
    @Transactional
    public AjaxResult offShop(@RequestParam("manyFiles") MultipartFile[] manyFiles,Long shopId, String handResult) throws Exception {
        if (!StringUtils.isNotEmpty(handResult) || !StringUtils.isNotNull(shopId)){
           return error("请认真填写");
        }
        ShopOffUser shopOffUser = new ShopOffUser();
        if (manyFiles != null) {//有营业执照
            for (MultipartFile file : manyFiles) {
                String upload = FileUploadUtils.upload(file);
                ImgFiles img = new ImgFiles();
                img.setImgName(file.getOriginalFilename());
                img.setImgPath(upload);
                imgFilesService.insertImgFiles(img);
                if (StringUtils.isNotEmpty(shopOffUser.getFileIds())) {

                    shopOffUser.setFileIds(shopOffUser.getFileIds() + "," + img.getId());
                } else {
                    shopOffUser.setFileIds(img.getId() + "");
                }
            }
        }
        WxShop wxShop = wxShopService.selectWxShopById(shopId);
        shopOffUser.setHandBy(getLoginName());
        shopOffUser.setHandResult(handResult);
        shopOffUser.setShopId(shopId);
        shopOffUser.setShopCompany(wxShop.getShopCompany());
        shopOffUser.setStatus("3");
        offUserService.insertShopOffUser(shopOffUser);
        return toOffShop(shopId,"3");
    }

    /**
     * 系统填写注销原因页面
     * */
    @GetMapping("/toHandResult/{shopId}")
    public String toHandResult(@PathVariable("shopId") Long shopId, ModelMap mmap) {
        mmap.put("shopId", shopId);
        return prefix + "/toHandResult";
    }
    /**
     * 根据注销类型和商铺id查询注销记录
     */
    @GetMapping("/lookHistory/{shopId}/{isValid}")
    public String lookHistory(@PathVariable("shopId") Long shopId, @PathVariable("isValid") String isValid, ModelMap mmap) {
        List<ShopOffUser> resultList = new ArrayList<>();
        if (isValid.equals("4")) {    //用户注销
            resultList = offUserService.queryOffListByShopId(shopId);
        }else {    //平台注销
            resultList = offUserService.queryOffListByShopId(shopId);
        }
        mmap.put("resultList", resultList);
        return prefix + "/lookHistory";
    }

    /**
     * 根据单位名称查询注销记录
     */
    @GetMapping("/lookByShopCompany")
    public String lookHistory(String shopCompany, ModelMap mmap) {
        ShopOffUser shopOffUser = new ShopOffUser();
        shopOffUser.setShopCompany(shopCompany);
        List<ShopOffUser> list = offUserService.selectShopOffUserList(shopOffUser);
        mmap.put("resultList", list);
        return prefix + "/lookHistory";
    }

    /**
     * 根据单位名称查询
     * @param shopCompany
     * @return
     */
    @RequestMapping("/queryByShopCompany")
    @ResponseBody
    public Object queryByShopCompany(String shopCompany) {
        ShopEntity shopEntity = wxShopService.queryByShopCompany(shopCompany,"1");
        if(StringUtils.isNotNull(shopEntity)){    //线上存在  需禁用
            return writeResultRep(shopEntity);
        }
        return writeResultFailure("单位名称可使用");
    }

    /*根据手机号查询用户*/
    @RequestMapping(value = "/searchUser")
    @ResponseBody
    public Object searchUser(String phoneNum) {

        WxUser wxUser =  wxUserService.queryByPhone(phoneNum);
        ShopSuser shopSuser = shopSuserService.selectOneShopId(getUserId());
        if (!StringUtils.isNotNull(shopSuser)){
            return writeResultFailure("无对应商铺,无法查询");
        }
        if (StringUtils.isNotNull(wxUser)){     //查询出用户
            ShopVo ss = shopSuserService.queryByWidAndSid(wxUser.getId(),shopSuser.getShopId());
            if (StringUtils.isNotNull(ss)){      //已经是商家员工
                return  writeResultFailure("请先在员工管理删除此员工");
            }
            return writeResultRep(wxUser);
        }
        return writeResultFailure("无此用户");
    }
    /*商铺转让*/
    @RequestMapping(value = "/changeShopWxUser")
    @ResponseBody
    @Transactional
    public Object changeShopWxUser(Long shopId,Long newWxUserId,Long wxUserId) {
        WxShop wxShop = wxShopService.selectWxShopById(shopId);
        wxShop.setWxUserId(newWxUserId);
        wxShopService.updateWxShop(wxShop);
        //1.查询出原先老板的关联关系
        ShopSuser shopSuser = shopSuserService.selectEntityByWidAndSid(wxUserId,shopId);
        //2.修改现在的老板关联关系
        shopSuser.setWxUserId(newWxUserId);
        return toAjax(shopSuserService.updateShopSuser(shopSuser));
    }
    /*=====================================================================================================================*/

    /**
     *
     * @param shopId    店铺id
     * @param code      3-平台注销  4-用户注销
     * @return
     * @throws Exception
     */
    public AjaxResult toOffShop(Long shopId, String code) throws Exception {
        List<ShopSuser> list = shopSuserService.queryByShopId(shopId);
        String[] strings = new String[list.size()];    //删除管理表数据的数组
        String[] str = new String[list.size()];    //删除管理表数据的数组
        for (int i = 0; i < list.size(); i++) {
            strings[i] = list.get(i).getId().toString();
            str[i] = list.get(i).getSysUserId().toString();
        }
        User user = sysUserService.selectUserById(list.get(0).getSysUserId());  //获取此系统用户绑定的部门
        deptService.deleteDeptById(user.getDeptId());    //删除部门

        sysUserService.deleteUserByIds(StringUtils.join(str, ","));   // 删除系统用户
        shopSuserService.deleteShopSuserByIds(StringUtils.join(strings, ","));  //删除关联表数据
        wxUserService.cleanShopId(shopId);  // 清除会员绑定的归属商家
        WxShop wxShop = new WxShop();
        wxShop.setId(shopId);
        wxShop.setIsValid(code);   //修改店铺状态
        return toAjax(wxShopService.updateWxShop(wxShop));
    }

}
